﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace TData
{
    public class DynamicList : List<dynamic>
    {
        public string ToJson()
        {
            if (this.Count == 0) return "";

            StringBuilder sb1 = new StringBuilder();
            sb1.Append("[");
            foreach (dynamic item in this)
            {
                StringBuilder sb2 = new StringBuilder();
                sb2.Append("{");

                ExpandoObject eo = item;
                var kvpList = eo.ToList();
                foreach (var kvp in kvpList)
                {
                    if (kvp.Value.GetType() == typeof(System.Byte[]))
                    {
                        byte[] bs = kvp.Value as byte[];
                        sb2.AppendFormat("\"{0}\":\"{1}\",", kvp.Key, FormatBytes(bs));
                    }
                    else
                    {
                        sb2.AppendFormat("\"{0}\":\"{1}\",", kvp.Key, kvp.Value);
                    }
                }
                string singleObjJSON = Regex.Replace(sb2.ToString(), @",$", "},");
                sb1.Append(singleObjJSON);
            }

            string json = Regex.Replace(sb1.ToString(), @",$", "]");
            return json;
        }

        private string FormatBytes(byte[] val)
        {
            if (val == null) return string.Empty;

            StringBuilder sb = new StringBuilder();
            sb.Append("0x");
            sb.Append(BitConverter.ToString(val).Replace("-", ""));

            return sb.ToString();
        }
    }
}
